using System;
using System.Collections.Generic;
using System.Text;
using CodePlex.SpaceBlock.FS;

namespace CodePlex.SpaceBlock.JobModel
{
    public class DeleteJob : BaseJob,  IJob
    {

        private readonly List<Path> _items;

     

        public DeleteJob(IFileSystem target)
            : base(target)
        {
            _items = new List<Path>();
        }

        public void Add(Path path)
        {
            _items.Add(path);
        }



       
        public void Execute()
        {
            UpdateCaption("Deleting...");
            UpdateProgress(0);

            int itemsCount = _items.Count;



            bool s3hack = false;
            S3FileSystem s3fs = this.TargetFS as S3FileSystem;
            if(s3fs != null && itemsCount > 0 ) 
            {
                Path firstParent = _items[0].Parent;
                s3hack = _items.TrueForAll(delegate(Path item) 
                {
                    return !item.IsFolder && item.Parent.Equals(firstParent);
                });



            }

            

            int i = 0;
            foreach (Path item in _items)
            {
                if (s3hack && i < itemsCount-1)
                {
                    s3fs.Delete(item, false);
                }
                else
                {
                    this.TargetFS.Delete(item);
                }

              
                this.UpdateTargetPath(item);

            
                i++;
                UpdateProgress(i, itemsCount);
                double pct = (double)i / (double)itemsCount;

                UpdateDescription("{2:0%} complete - deleted {0} of {1} items", i, itemsCount, pct);
            }

            UpdateProgress(100);
            UpdateCaption("Deletion complete.");
        }


        public string GetFrom()
        {
            return null;
        }

        public string GetSpeed()
        {
            return "n/a";
        }



        public long? GetSize()
        {
            return null;
        }
        public long? GetTransferred()
        {
            return null;
        }

       
    }
}
